package com.db.connection;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Properties;

public class DBCPPostgresMikeManager {
	private static BasicDataSource ds = null;

	public DBCPPostgresMikeManager() {
	}
	
	static {
		if (ds != null) {
			try {
				ds.close();
			} catch (Exception e) {
				//
			}
			ds = null;
		}

		try {
			Properties p = new Properties();
			p.load(DBCPPostgresMikeManager.class.getResourceAsStream("dbcp_postgres_mike.properties"));
			ds = (BasicDataSource) BasicDataSourceFactory.createDataSource(p);

		} catch (Exception e) {
			//
		}
	}

	public static void main(String[] args) {
//		init();

		try {
			for (int i = 0; i < 10000; i++) {
				Connection con = getConnection();// ���l��

				try {
					Statement stmt = null;
					ResultSet rs = null;
					stmt = con.createStatement();
					rs = stmt.executeQuery("select * from ad_user");
					while (rs.next()) {
						System.out.println(rs.getString(1));
					}

					close(stmt, rs);					
				} catch (Exception e) {
					e.printStackTrace();
				}
				con.close();// �ͷ�l��
			}
			// dataSource.

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void close(Statement pstmt, ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	
	public static void close(Connection conn, Statement pstmt, ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void init() {

		if (ds != null) {
			try {
				ds.close();
			} catch (Exception e) {
				//
			}
			ds = null;
		}

		try {
			Properties p = new Properties();
			p.load(DBCPPostgresMikeManager.class.getResourceAsStream("dbcp_postgres.properties"));
			ds = (BasicDataSource) BasicDataSourceFactory.createDataSource(p);

		} catch (Exception e) {
			//
		}
	}

	public static synchronized Connection getConnection() throws SQLException {

		Connection conn = null;
		if (ds != null) {
			conn = ds.getConnection();// ���l��
		}
		conn.setAutoCommit(false);
		return conn;
	}
}
